package com.stylefeng.guns.rest.modular.order;

import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.api.alipay.AlipayServiceApi;
import com.stylefeng.guns.api.alipay.vo.AlipayInfoVO;
import com.stylefeng.guns.api.alipay.vo.AlipayResultVO;
import com.stylefeng.guns.api.order.OrderServiceApi;
import com.stylefeng.guns.api.order.vo.OrderVO;
import com.stylefeng.guns.core.util.TokenBucket;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.rest.common.CurrentUser;
import com.stylefeng.guns.rest.modular.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/order/")
@Slf4j
public class OrderController {

    private static TokenBucket tokenBucket = new TokenBucket();

    private static final String imgPre = "http://img.meetingshop.cn/";

    @DubboReference(check = false)
    private OrderServiceApi orderServiceApi;

    @DubboReference(check = false)
    private AlipayServiceApi alipayServiceApi;

//    @DubboReference(check = false, group = "2017")
//    OrderServiceApi orderServiceApi2017;

    @RequestMapping(value = "buyTickets", method = RequestMethod.POST)
    public ResponseVO buyTickets(Integer fieldId, String soldSeats, String seatsName){
        if (tokenBucket.getToken()){
            try{
                boolean isTrue = orderServiceApi.isTrueSeats(fieldId + "", soldSeats);
                boolean isNotSold = orderServiceApi.isNotSoldSeats(fieldId + "", soldSeats);
                if (isNotSold && isTrue){
                    String userId = CurrentUser.getUserId();
                    if (userId == null || userId.trim().length() == 0){
                        return ResponseVO.serviceFail("用户未登录");
                    }
                    OrderVO orderVO = orderServiceApi.saveOrderInfo(fieldId, soldSeats, seatsName, Integer.parseInt(userId));
                    if (orderVO == null){
                        log.error("购票业务异常");
                        return ResponseVO.serviceFail("购票业务异常");
                    }else{
                        return ResponseVO.success(orderVO);
                    }
                }else{
                    return ResponseVO.serviceFail("订单中的座位号有问题");
                }

            }catch (Exception e){
                log.error("购票业务异常", e);
                return ResponseVO.appFail("购票业务异常");
            }
        }else {
            return ResponseVO.serviceFail("当前购票人数过多，请稍后再试");
        }


    }

    @RequestMapping(value = "getOrderInfo", method = RequestMethod.POST)
    public ResponseVO getOrderInfo(
            @RequestParam(value = "nowPage", required = false, defaultValue = "1") Integer nowPage,
            @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize
    ){
        String userId = CurrentUser.getUserId();
        Page<OrderVO> page = new Page<>(nowPage, pageSize);

        if (userId != null || userId.trim().length() > 0){
            List<Page<OrderVO>> orderByUserId = orderServiceApi.getOrderByUserId(Integer.parseInt(userId), page);
//            Page<OrderVO> orderByUserId2017 = orderServiceApi2017.getOrderByUserId(Integer.parseInt(userId), page);
//            List<OrderVO> orderVOList = new ArrayList<>();
//            int totals = (int)(orderByUserId.getPages() + orderByUserId2017.getPages());
            int totals = 0;
//            orderVOList.addAll(orderByUserId.getRecords());
//            orderVOList.addAll(orderByUserId2017.getRecords());

            return ResponseVO.success(nowPage, totals, "", orderByUserId);
        }else{
            return ResponseVO.serviceFail("用户未登录");
        }

    }

    @RequestMapping(value = "getPayInfo", method = RequestMethod.POST)
    public ResponseVO getPayInfo(@RequestParam("orderId") String orderId){
        String userId = CurrentUser.getUserId();
        if (userId == null || userId.trim().length() == 0){
            return ResponseVO.serviceFail("用户未登录");
        }
        AlipayInfoVO qrCode = alipayServiceApi.getQRCode(orderId);

        return ResponseVO.success(imgPre, qrCode);
    }

    @RequestMapping(value = "getPayResult", method = RequestMethod.POST)
    public ResponseVO getPayResult(@RequestParam("orderId") String orderId,
                                   @RequestParam(value = "tryNums", required = false, defaultValue = "1") Integer tryNums){
        String userId = CurrentUser.getUserId();
        if (userId == null || userId.trim().length() == 0){
            return ResponseVO.serviceFail("用户未登录");
        }
        RpcContext.getContext().setAttachment("userId", userId);
        if (tryNums >= 4){
            return ResponseVO.serviceFail("支付失败，请稍后重试");
        }else {
            AlipayResultVO alipayResultVO = alipayServiceApi.getOrderStatus(orderId);
            if (alipayResultVO == null || ToolUtil.isEmpty(alipayResultVO.getOrderId())){
                AlipayResultVO serviceFail = new AlipayResultVO();
                serviceFail.setOrderId(orderId);
                serviceFail.setOrderStatus(0);
                serviceFail.setOrderMsg("支付失败");

                return ResponseVO.success(serviceFail);
            }
            return ResponseVO.success(alipayResultVO);
        }


    }

}
